import csv
import schedule
import time
from threading import Thread
#from prompt import summary
from datetime import datetime, timedelta
import os
#from newprompt import summary
from lang_prompt import summary
import re

# 检查文件是否存在，如果不存在则创建一个空文件
if not os.path.exists("messages.csv"):
    with open("messages.csv", "w", newline="", encoding="utf-8") as csvfile:
        pass

#将收到的消息缓存到csv文件，并且从csv文件里读取消息。

chat_record = []

def add_message(msg):
    global chat_record
    chat_record.append(msg)
    if len(chat_record) >= 20:
        write_messages_to_csv()
        chat_record = []
        

def write_messages_to_csv():
    with open('messages.csv', 'a', newline='', encoding='utf-8') as csvfile:
        writer = csv.writer(csvfile)
        for msg in chat_record:
            writer.writerow([msg['eventType'], msg['eventData']['msgType'], msg['eventData']['sessionId'], msg['eventData']['uuid'], msg['eventData']['notify'], msg['eventData']['addtime'], msg['eventData']['sessionType'], msg['eventData']['from'], msg['eventData']['to']])
        chat_record.clear()


#处理@某人的消息，把@某人的信息去除掉。
def message_preprocess(input_string):
    while '@' in input_string:
        start = input_string.find('@')
        end = input_string.find(' ', start)
        if end == -1:  # 没有找到空格字符
            input_string = input_string[:start]
        else:
            input_string = input_string[:start] + input_string[end+1:]

#    input_string = "这是文本[doc]https://docs.popo.netease.com/lingxi/example#edit[/doc]这是另一段文本[img]https://example.com/image.jpg[/img]另外一个URL: https://openai.com 最后的文本"

# 使用正则表达式删除以[doc]或[img]开头并以[/doc]或[/img]结尾的子字符串
    
    #result = re.sub(r'(\[(doc|img)\].*?\[\/(doc|img)\])|(https?://\S+)', '', input_string)

    # Combine multiple regex patterns into a single pattern
    patterns = [
        r'(\[(doc|img)\].*?\[\/(doc|img)\])',    # Existing pattern for [doc] or [img] tags
        r'(https?://\S+)',                        # Existing pattern for URLs
        r'<[^>]+>',                               # HTML tags
        r'\[emts\].*?\[\/emts\]',                 # Custom emoticon tags
    ]
    combined_pattern = '|'.join(patterns)
    result = re.sub(combined_pattern, '', input_string)

    # 使用re.sub函数替换连续的换行符
    result = re.sub('\n+', '\n', result)
    
    # Remove extra whitespaces, tabs, and newlines
    result = ' '.join(result.split())
    
    return result

message_preprocess('1')

#读取所有群消息
def read_all_messages_from_csv(date):
    messages_from_csv = []
    with open('messages.csv', 'r', newline='', encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            msg_date = row[5].split(' ')[0]
            msgType = row[1]
            if msg_date == date and msgType != '128' and msgType != '133' and row[4] != '暂不支持解析的消息类型':
                notify_value = message_preprocess(row[4])
                messages_from_csv.append({
                    'eventType': row[0],
                    'eventData': {
                        'msgType': int(row[1]),
                        'sessionId': row[2],
                        'uuid': row[3],
                        'notify': notify_value,
                        'addtime': row[5],
                        'sessionType': int(row[6]),
                        'from': row[7],
                        'to': row[8]
                    }
                })
    return messages_from_csv

#读取指定群消息
def read_certain_messages_from_csv(date,target_id):
    messages_from_csv = []
    with open('messages.csv', 'r', newline='', encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            msg_date = row[5].split(' ')[0]
            msgType = row[1]
            sessionid = row[2]
            if msg_date == date and target_id == sessionid and msgType != '128' and msgType != '133' and row[4] != '暂不支持解析的消息类型':
                notify_value = message_preprocess(row[4])
                messages_from_csv.append({
                    'eventType': row[0],
                    'eventData': {
                        'msgType': int(row[1]),
                        'sessionId': row[2],
                        'uuid': row[3],
                        'notify': notify_value,
                        'addtime': row[5],
                        'sessionType': int(row[6]),
                        'from': row[7],
                        'to': row[8]
                    }
                })
    return messages_from_csv


#总结指定日期的结果
def summarize_all_messages(date):
    write_messages_to_csv()
    all_messages = read_all_messages_from_csv(date)

    # 创建一个以sessionId为键的字典
    messages_by_session = {}
    for message in all_messages:
        session_id = message['eventData']['sessionId']
        if session_id in messages_by_session:
            messages_by_session[session_id].append(message)
        else:
            messages_by_session[session_id] = [message]

    # 创建一个新的字典来保存结果
    results = {}
    for session_id, messages in messages_by_session.items():
        print(session_id)
        # 将summary函数的结果保存为sessionId的值
        summary_result = summary(messages)
        if summary_result == "服务出错":
            return '服务出错'
        else:
            results[session_id] = summary_result

    # 这个函数现在返回一个字典，其中每个sessionId都有一个对应的摘要
    return results

#总结指定群，指定日期的结果。直接返回结果即可
def summarize_certain_messages(date, target_list):
    write_messages_to_csv()
    results = {}
    for target_id in target_list:
        messages = read_certain_messages_from_csv(date, target_id)        

        # 为每一个target_id创建一个摘要
        summary_result = summary(messages)
        if summary_result == "服务出错":
            return '服务出错'
        else:
            results[target_id] = summary_result
    
    # 这个函数现在返回一个字典，其中每个target_id都有一个对应的摘要
    return results


# def summarize_group_messages():
#     write_messages_to_csv()
#     all_messages = read_messages_from_csv()

#     # 需要根据群ID来做一个字典。
#     # 这里调用群消息总结函数
#     result = summary(all_messages)
#     print(result)
#     # 清空 messages 列表和 CSV 文件中的消息    
#     # 清空CSV文件
#     # with open("messages.csv", "w", newline="", encoding="utf-8"):
#     #     pass
#     return result

